package com.igbeok.miscellaneous.concurrency.hemberg;

public class Cooker implements Runnable {
	// 厨师要面对容器
	HambergFifo pool;
	// 还要面对服务生
	Waiter waiter;

	public Cooker(Waiter waiter, HambergFifo hambergStack) {
		this.pool = hambergStack;
		this.waiter = waiter;
	}

	// 制造汉堡
	public void makeHamberg() {
		// 制造的个数
		int madeCount = 0;
		// 因为容器满，被迫等待的次数
		int fullFiredCount = 0;
		try {

			while (true) {
				// 制作汉堡前的准备工作
				//Thread.sleep(1000);
				if (pool.size() < pool.getMaxSize()) {
					synchronized (waiter) {
						// 容器未满，制作汉堡，并放入容器。
						pool.push(new Hamberg(++madeCount, Thread.currentThread().getName()));
						// 说出容器内汉堡数量
						System.out.println(Thread.currentThread().getName() + ": There are " + pool.size()
								+ " Hambergs in all");
						// 让服务生通知顾客，有汉堡可以吃了
						waiter.notifyAll();
						System.out.println("### Cooker: waiter.notifyAll() :"
								+ " Hi! Customers, we got some new Hambergs!");
					}
				} else {
					synchronized (pool) {
						if (fullFiredCount++ < 10) {
							// 发现容器满了，停止做汉堡的尝试。
							System.out.println(Thread.currentThread().getName()
									+ ": Hamberg Pool is Full, Stop making hamberg");
							System.out.println("### Cooker: pool.wait()");
							// 汉堡容器的状况使厨师等待
							pool.wait();
						} else {
							return;
						}
					}

				}

				// 做完汉堡要进行收尾工作，为下一次的制作做准备。
				Thread.sleep(1000);

			}
		} catch (Exception e) {
			madeCount--;
			e.printStackTrace();
		}
	}

	public void run() {

		makeHamberg();

	}
}
